/*
 * @Author: your name
 * @Date: 2021-11-21 13:33:48
 * @LastEditTime: 2021-11-21 13:49:23
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\serve\app\controller\oss.js
 */
// app/controller/common.js
"use strict";

const Controller = require("egg").Controller;
const fs = require("mz/fs");
const path = require("path");
class CommonController extends Controller {
    // 上传
    async upload() {
        const ctx = this.ctx;
        if (!ctx.request.files) {
            ctx.body = "请先选择上传文件";
        }
        const file = ctx.request.files[0];
        console.log(file);
        // const name = 'egg-oss-demo/' + path.basename(file.filename);
        const name = "图片/" + Date.now() + path.extname(file.filename);
        let result;
        try {
            result = await ctx.oss.put(name, file.filepath);
        } catch (err) {
            console.log(err);
        } finally {
            await fs.unlink(file.filepath);
        }

        if (result) {
            return ctx.apiSuccess(result.url);
        }

        ctx.body = "上传失败";
    }
}

module.exports = CommonController;